<template>
  <div class="register-page">
    <Header />

    <!-- 注册内容区域 -->
    <div class="register-content">
      <div class="container">
        <div class="register-wrapper">
          <!-- 左侧品牌信息 -->
          <div class="brand-section">
            <div class="brand-content">
              <img src="@/assets/logo-full.png" alt="六堡茶" class="brand-logo" />
              <h2 class="brand-title">加入我们</h2>
              <p class="brand-desc">注册成为会员，享受更多专属权益</p>
              <div class="brand-benefits">
                <div class="benefit-item">
                  <span class="benefit-icon">🎁</span>
                  <div class="benefit-text">
                    <h4>新人礼包</h4>
                    <p>注册即送优惠券</p>
                  </div>
                </div>
                <div class="benefit-item">
                  <span class="benefit-icon">⭐</span>
                  <div class="benefit-text">
                    <h4>会员积分</h4>
                    <p>购买商品获得积分</p>
                  </div>
                </div>
                <div class="benefit-item">
                  <span class="benefit-icon">🚀</span>
                  <div class="benefit-text">
                    <h4>专享服务</h4>
                    <p>优先客服支持</p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧注册表单 -->
          <div class="form-section">
            <div class="form-container">
              <div class="form-header">
                <h3 class="form-title">用户注册</h3>
                <p class="form-subtitle">创建您的六堡茶账户</p>
              </div>

              <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" class="register-form" @submit.prevent="handleRegister">
                <el-form-item prop="username">
                  <el-input v-model="registerForm.username" placeholder="请输入用户名" size="large" prefix-icon="User" clearable />
                </el-form-item>

                <el-form-item prop="phone">
                  <el-input v-model="registerForm.phone" placeholder="请输入手机号" size="large" prefix-icon="Phone" clearable />
                </el-form-item>

                <el-form-item prop="verifyCode">
                  <div class="verify-code-wrapper">
                    <el-input v-model="registerForm.verifyCode" placeholder="请输入验证码" size="large" prefix-icon="Message" clearable />
                    <el-button class="verify-btn" :disabled="countdown > 0" @click="sendVerifyCode">
                      {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
                    </el-button>
                  </div>
                </el-form-item>

                <el-form-item prop="password">
                  <el-input
                    v-model="registerForm.password"
                    type="password"
                    placeholder="请输入密码"
                    size="large"
                    prefix-icon="Lock"
                    show-password
                    clearable />
                </el-form-item>

                <el-form-item prop="confirmPassword">
                  <el-input
                    v-model="registerForm.confirmPassword"
                    type="password"
                    placeholder="请确认密码"
                    size="large"
                    prefix-icon="Lock"
                    show-password
                    clearable />
                </el-form-item>

                <el-form-item prop="agreement">
                  <el-checkbox v-model="registerForm.agreement">
                    我已阅读并同意
                    <a href="#" class="agreement-link" @click.prevent="showAgreement">《用户协议》</a>
                    和
                    <a href="#" class="agreement-link" @click.prevent="showPrivacy">《隐私政策》</a>
                  </el-checkbox>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" size="large" class="register-btn" :loading="loading" @click="handleRegister">
                    {{ loading ? '注册中...' : '立即注册' }}
                  </el-button>
                </el-form-item>

                <div class="form-footer">
                  <span class="login-text">已有账户？</span>
                  <router-link to="/login" class="login-link">立即登录</router-link>
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户协议弹窗 -->
    <el-dialog v-model="agreementVisible" title="用户协议" width="80%" max-width="600px">
      <div class="agreement-content">
        <h4>1. 服务条款</h4>
        <p>欢迎使用六堡茶商城服务。在使用我们的服务前，请仔细阅读本协议。</p>

        <h4>2. 账户注册</h4>
        <p>用户需要提供真实、准确的个人信息进行注册，并对账户安全负责。</p>

        <h4>3. 商品购买</h4>
        <p>用户在本平台购买的商品需遵守相关法律法规，我们保证商品质量。</p>

        <h4>4. 隐私保护</h4>
        <p>我们承诺保护用户隐私，不会泄露用户个人信息。</p>

        <h4>5. 免责声明</h4>
        <p>在法律允许的范围内，我们对因使用本服务而产生的损失不承担责任。</p>
      </div>
      <template #footer>
        <el-button @click="agreementVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 隐私协议弹窗 -->
    <el-dialog v-model="privacyVisible" title="隐私协议" width="80%" max-width="600px">
      <div class="agreement-content">
        <h4>1. 服务条款</h4>
        <p>欢迎使用六堡茶商城服务。在使用我们的服务前，请仔细阅读本协议。</p>

        <h4>2. 账户注册</h4>
        <p>用户需要提供真实、准确的个人信息进行注册，并对账户安全负责。</p>

        <h4>3. 商品购买</h4>
        <p>用户在本平台购买的商品需遵守相关法律法规，我们保证商品质量。</p>

        <h4>4. 隐私保护</h4>
        <p>我们承诺保护用户隐私，不会泄露用户个人信息。</p>

        <h4>5. 免责声明</h4>
        <p>在法律允许的范围内，我们对因使用本服务而产生的损失不承担责任。</p>
      </div>
      <template #footer>
        <el-button @click="privacyVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <Footer />
  </div>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import { useUserStore } from '@/stores/user.js'
  import apiUser from '@/api/modules/user'

  const router = useRouter()
  const userStore = useUserStore()
  const registerFormRef = ref()
  const loading = ref(false)
  const countdown = ref(0)
  const agreementVisible = ref(false)
  const privacyVisible = ref(false)

  // 注册表单数据
  const registerForm = reactive({
    username: '',
    phone: '',
    verifyCode: '',
    password: '',
    confirmPassword: '',
    agreement: false,
  })

  // 自定义验证函数
  const validateConfirmPassword = (rule, value, callback) => {
    if (value !== registerForm.password) {
      callback(new Error('两次输入的密码不一致'))
    } else {
      callback()
    }
  }

  const validatePhone = (rule, value, callback) => {
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }

  // 表单验证规则
  const registerRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
      { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名只能包含字母、数字、下划线和中文', trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: validatePhone, trigger: 'blur' },
    ],
    verifyCode: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { len: 6, message: '验证码为6位数字', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
      { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' },
    ],
    confirmPassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: validateConfirmPassword, trigger: 'blur' },
    ],
    agreement: [
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback(new Error('请阅读并同意用户协议'))
          } else {
            callback()
          }
        },
        trigger: 'change',
      },
    ],
  }

  // 发送验证码
  const sendVerifyCode = async () => {
    if (!registerForm.phone) {
      ElMessage.warning('请先输入手机号')
      return
    }

    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(registerForm.phone)) {
      ElMessage.warning('请输入正确的手机号')
      return
    }

    try {
      apiUser
        .GetRegisterVerifyCode({
          mobile: registerForm.phone,
        })
        .then(async (res) => {
          ElMessage.success('验证码已发送')

          // 开始倒计时
          countdown.value = 60
          const timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        })
        .catch((err) => {})
    } catch (error) {
      console.error('发送验证码失败:', error)
      ElMessage.error('发送验证码失败，请稍后重试')
    }
  }

  // 处理注册
  const handleRegister = async () => {
    if (!registerFormRef.value) return

    try {
      const valid = await registerFormRef.value.validate()
      if (!valid) return

      loading.value = true

      // 调用用户store的注册方法
      const result = await userStore.register({
        username: registerForm.username,
        mobile: registerForm.phone,
        password: registerForm.password,
        captcha: registerForm.verifyCode,
      })

      if (result.success) {
        ElMessage.success('注册成功！正在为您自动登录...')

        // 注册成功后自动跳转到用户中心
        setTimeout(() => {
          router.push('/user')
        }, 1500)
      } else {
        ElMessage.error(result.error || '注册失败，请稍后重试')
      }
    } catch (error) {
      console.error('注册失败:', error)
      ElMessage.error('注册失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }

  // 显示用户协议
  const showAgreement = () => {
    agreementVisible.value = true
  }

  // 显示隐私政策
  const showPrivacy = () => {
    privacyVisible.value = true
  }
</script>

<style scoped>
  .register-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  }

  .register-content {
    padding: 60px 0;
    min-height: calc(100vh - 200px);
    display: flex;
    align-items: center;
  }

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }

  .register-wrapper {
    display: flex;
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    min-height: 700px;
  }

  /* 左侧品牌区域 */
  .brand-section {
    flex: 1;
    background: linear-gradient(135deg, #1c705e 0%, #2d8a6e 100%);
    color: white;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .brand-content {
    text-align: center;
    max-width: 400px;
  }

  .brand-logo {
    width: 120px;
    height: auto;
    margin-bottom: 30px;
    background: white;
    padding: 15px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .brand-title {
    font-size: 32px;
    font-weight: 600;
    margin-bottom: 16px;
    color: white;
  }

  .brand-desc {
    font-size: 16px;
    opacity: 0.9;
    margin-bottom: 40px;
    line-height: 1.6;
  }

  .brand-benefits {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }

  .benefit-item {
    display: flex;
    align-items: center;
    gap: 16px;
    text-align: left;
  }

  .benefit-icon {
    font-size: 24px;
    flex-shrink: 0;
  }

  .benefit-text h4 {
    font-size: 16px;
    font-weight: 600;
    margin: 0 0 4px 0;
  }

  .benefit-text p {
    font-size: 14px;
    opacity: 0.8;
    margin: 0;
  }

  /* 右侧表单区域 */
  .form-section {
    flex: 1;
    padding: 60px 40px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form-container {
    width: 100%;
    max-width: 400px;
  }

  .form-header {
    text-align: center;
    margin-bottom: 40px;
  }

  .form-title {
    font-size: 28px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }

  .form-subtitle {
    color: #666;
    font-size: 14px;
  }

  .register-form {
    margin-bottom: 30px;
  }

  .register-form .el-form-item {
    margin-bottom: 20px;
  }

  .verify-code-wrapper {
    display: flex;
    gap: 12px;
  }

  .verify-code-wrapper .el-input {
    flex: 1;
  }

  .verify-btn {
    white-space: nowrap;
    min-width: 120px;
  }

  .agreement-link {
    color: #1c705e;
    text-decoration: none;
  }

  .agreement-link:hover {
    text-decoration: underline;
  }

  .register-btn {
    width: 100%;
    height: 48px;
    font-size: 16px;
    font-weight: 600;
    background: #1c705e;
    border-color: #1c705e;
  }

  .register-btn:hover {
    background: #2d8a6e;
    border-color: #2d8a6e;
  }

  .form-footer {
    text-align: center;
    font-size: 14px;
    color: #666;
  }

  .login-link {
    color: #1c705e;
    text-decoration: none;
    font-weight: 600;
    margin-left: 8px;
  }

  .login-link:hover {
    text-decoration: underline;
  }

  /* 协议内容 */
  .agreement-content {
    max-height: 400px;
    overflow-y: auto;
    padding: 20px;
    line-height: 1.6;
  }

  .agreement-content h4 {
    color: #1c705e;
    margin: 20px 0 10px 0;
  }

  .agreement-content h4:first-child {
    margin-top: 0;
  }

  .agreement-content p {
    margin-bottom: 15px;
    color: #666;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .register-wrapper {
      flex-direction: column;
      margin: 20px;
    }

    .brand-section {
      padding: 40px 20px;
    }

    .form-section {
      padding: 40px 20px;
    }

    .brand-title {
      font-size: 24px;
    }

    .form-title {
      font-size: 24px;
    }

    .verify-code-wrapper {
      flex-direction: column;
    }

    .verify-btn {
      min-width: auto;
    }
  }

  @media (max-width: 480px) {
    .register-content {
      padding: 20px 0;
    }

    .container {
      padding: 0 10px;
    }

    .brand-section,
    .form-section {
      padding: 30px 15px;
    }
  }
</style>
